package com.launcher.wkang.activity;


import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkRequest;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.codbking.calendar.exaple.MainActivity;
import com.google.gson.Gson;
import com.launcher.wkang.App;
import com.launcher.wkang.R;
import com.launcher.wkang.adapter.LauncherAdapter;
import com.launcher.wkang.bean.CouListBean;
import com.launcher.wkang.bean.CourseBean;
import com.launcher.wkang.bean.TimeBean;
import com.launcher.wkang.bean.WeatherBean;
import com.launcher.wkang.fragment.Fragment1;
import com.launcher.wkang.receive.PushReceive;
import com.launcher.wkang.service.ContactService;
import com.launcher.wkang.util.NetUtils;
import com.launcher.wkang.util.PhoneUtil;
import com.launcher.wkang.util.Url;
import com.launcher.wkang.view.LauncherFragment;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static cn.jpush.android.api.JPushInterface.getRegistrationID;

//import io.rong.imlib.RongIMClient;

public class LauncherActivity1 extends FragmentActivity  {

    private LauncherFragment launcherFragment;
    private String hintText;
    private HomeWatcherReceiver homeWatcherReceiver;
    private IntentFilter homeFilter;
    public   WeatherBean weatherBean;
    private  Timer doProhibitTimer;
    private  TimerTask doProhibitTimerTask;
    private final int SETDEFAULTITEM=1001;
    private final int HINTTEXTWHAT=1002;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_launcher1);
        initView();
        initData();
//        new  Prohibit().
        initRegionId();
    }

    private void initView() {
        launcherFragment=findViewById(R.id.frame_content);
    }
    public void doProhibit(){
        if (phoneDisable()){
            if(!isMainActivityTop()) {
                goHome();
            }
            App.getINstance().isProhibit=true;
            Message message=new Message();
            message.arg1=SETDEFAULTITEM;
            doProhibitHandle.sendMessage(message);
            Log.d("LauncherActivity1","isProhibit="+true+"launcherFragment.setCurrentItem(0);");
        }else {
            App.getINstance().isProhibit=false;
            Log.d("LauncherActivity1","isProhibit="+false);
        }
        Message message=new Message();
        message.arg1=HINTTEXTWHAT;
        doProhibitHandle.sendMessage(message);
    }
    private void goHome(){
        Message message=new Message();
        message.arg1=SETDEFAULTITEM;
        doProhibitHandle.sendMessage(message);
        Intent intent = new Intent();
// 为Intent设置Action、Category属性
        intent.setAction(Intent.ACTION_MAIN);// "android.intent.action.MAIN"
        intent.addCategory(Intent.CATEGORY_HOME); //"android.intent.category.HOME"
        startActivity(intent);
    }
    /**
          *
          * 判断mainactivity是否处于栈顶
          * @return  true在栈顶false不在栈顶
          */
    private boolean isMainActivityTop(){
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        String name = manager.getRunningTasks(1).get(0).topActivity.getClassName();
        return name.equals(LauncherActivity1.class.getName());
    }


    /**
     * 时间段禁用
     * @return
     */
    private boolean slotDisable() {
        SharedPreferences sharedPreferences = getSharedPreferences(getPackageName(), Context.MODE_PRIVATE);
        int disableClass = sharedPreferences.getInt("disableClass", 0);
        String amstarttime = sharedPreferences.getString("amstarttime", null);
        String amendtime = sharedPreferences.getString("amendtime", null);

        String pmstarttime = sharedPreferences.getString("pmstarttime", null);
        String pmendtime = sharedPreferences.getString("pmendtime", null);


        String gnstarttime = sharedPreferences.getString("gnstarttime", null);
        String gnendtime = sharedPreferences.getString("gnendtime", null);

        String repeat = sharedPreferences.getString("repeat", null);
        Calendar cal = Calendar.getInstance();
        int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (week_index == 0) {
            week_index = 7;
        }

        if (null!=repeat) {
            String[] itemStrs = repeat.split(",");
            if (itemStrs != null && itemStrs.length > 0)
            {
                for (int j = 0; j < itemStrs.length; j++) {
                    try {

                        int repeatItem = Integer.valueOf(itemStrs[j]);
                        if (repeatItem == week_index) {
                            boolean isInAmTime = isEffectiveDate(amstarttime, amendtime);
                            boolean isInPmtime = isEffectiveDate(pmstarttime, pmendtime);
                            boolean isInGnTime = isEffectiveDate(gnstarttime, gnendtime);
                            return isInAmTime || isInPmtime || isInGnTime;
                        }
                    } catch (NumberFormatException e) {

                    }
                }
            }
        }
        return false;

    }
    private boolean phoneDisable(){
        SharedPreferences sharedPreferences = getSharedPreferences(getPackageName(), Context.MODE_PRIVATE);
        int disableClass = sharedPreferences.getInt("disableClass", 0);
        String lostStatus=sharedPreferences.getString("lostStatus",null);
        String electricityStatus=sharedPreferences.getString("electricityStatus",null);
        int current = sharedPreferences.getInt("current",-1);// 获得当前电量
        int total = sharedPreferences.getInt("total",-1);// 获得总电量
        if (disableClass==1){
            if (courseDisabled()){
                hintText="上课时间请专心听讲";
                App.getINstance().isAnswer=false;
                return true;
            }
        }
        if (disableClass==2){
            if (slotDisable()){
                hintText="上课时间请专心听讲";
                App.getINstance().isAnswer=false;
                return true;
            }
        }
//        如果之前两个条件不成立说明上课禁用功能不成立
        App.getINstance().isAnswer=true;
        if ("1".equalsIgnoreCase(lostStatus)){
            hintText="不是自己手机请归还失主噢";
            return true;
        }
        if ("1".equalsIgnoreCase(electricityStatus)){
            float present=(float) current/(float) total;
            if (current*10<total||current*10==total) {
                hintText = "手机电量低";
                return true;
            }
        }
        return false;
    }
    /**
     * 课程表禁用
     */
    private boolean courseDisabled(){

        SharedPreferences sharedPreferences = getSharedPreferences(getPackageName(), Context.MODE_PRIVATE);
        String  couList = sharedPreferences.getString("couList", null);
        if (!TextUtils.isEmpty(couList)) {
            Gson gson = new Gson();
            final CouListBean couListBean = gson.fromJson(couList, CouListBean.class);
            if (couListBean != null) {
                ArrayList<TimeBean> dateList = couListBean.getDateList();
                if (dateList != null && dateList.size() > 0) {
                    boolean isIntime = false;
                    for (int j = 0; j < dateList.size(); j++) {
                        TimeBean timeBean = dateList.get(j);
                        String startTime = timeBean.getStartTime();
                        String format = "HH:mm";

                        isIntime = isEffectiveDate(startTime, null);
                        if (isIntime) {
                            Calendar cal = Calendar.getInstance();
                            int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
                            if (week_index == 0) {
                                week_index = 7;
                            }
                            ArrayList<ArrayList<CourseBean>> courseList = couListBean.getList();
                            if (courseList != null) {
                                ArrayList<CourseBean> courseBeans = courseList.get(week_index - 1);
                                if (courseBeans != null) {
                                    CourseBean courseBean = courseBeans.get(j);
                                    if (courseBean != null) {
                                        String courseName = courseBean.getCourseName();
                                        if (!TextUtils.isEmpty(courseName)) {
                                            Log.d("courseDisabled", "courseDisabled is true");
                                            return true;
                                        }
                                    }
                                }
                            }


                        }


                    }
                }

            }
        }
        Log.d("courseDisabled","courseDisabled is false");
        return false;

    }

    /**
     * 判断当前时间是否在[startTime, endTime]区间，注意时间格式要一致
     *
     * @param
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return
     * @author jqlin
     */
    public static boolean isEffectiveDate(String  startTime, String endTime) {

        String format = "HH:mm";
        Calendar nawDate = Calendar.getInstance();
        try {
            Date startTimeDate = new SimpleDateFormat(format).parse(startTime);
            int startHour=startTimeDate.getHours();
            int startMinute=startTimeDate.getMinutes();
            Log.d("LauncherActivity","startHour="+startHour+"#####startMinute="+startMinute);
            Calendar begin = Calendar.getInstance();
            begin.set(Calendar.HOUR_OF_DAY,startHour);
            begin.set(Calendar.MINUTE,startMinute+1);
            Calendar end = Calendar.getInstance();
            if (!TextUtils.isEmpty(endTime)) {
                Date endTimeDate = new SimpleDateFormat(format).parse(endTime);
                int endHour=endTimeDate.getHours();
                int endMinute=endTimeDate.getMinutes();
                end.set(Calendar.HOUR_OF_DAY,endHour);
                end.set(Calendar.MINUTE,endMinute+1);
            }else {
                end.set(Calendar.HOUR_OF_DAY,startHour);
                end.set(Calendar.MINUTE,startMinute+1);
                end.add(Calendar.MINUTE, 45);
                int hour=end.get(Calendar.HOUR_OF_DAY);
                int minute=end.get(Calendar.MINUTE);
                Log.d("LauncherActivity","hour="+hour+"#####minute="+minute);

            }
//        end.add(Calendar.MINUTE, 45);
            boolean isAfter=nawDate.after(begin);
            boolean isBefore=nawDate.before(end);
            if (isAfter && isBefore) {
                return true;
            } else {
                return false;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean onGenericMotionEvent(MotionEvent event) {
        return super.onGenericMotionEvent(event);
    }



    private void initData() {
        PhoneUtil.setStatusBarFullTransparent(this);
        PhoneUtil.setAndroidNativeLightStatusBar(this,true);
        Intent intent = new Intent(this, ContactService.class);
        startService(intent);
        String registerId = getRegistrationID(this);
        homeWatcherReceiver=new HomeWatcherReceiver();
        homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        registerReceiver(homeWatcherReceiver, homeFilter);
        doProhibitTimer=new Timer();
        doProhibitTimerTask=new ProhibitTimerTask();
        doProhibitTimer.schedule(doProhibitTimerTask,0,10000);
    }
    @Override
    protected void onResume() {
        super.onResume();
        App.getINstance().setsetWaveformMode(2,1);
        new android.os.Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                App.getINstance().setsetWaveformMode(5,1);
//                        App.getINstance().setsetWaveformMode(1,1);
            }
        },100);
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(homeWatcherReceiver);
        super.onDestroy();
    }

    private class HomeWatcherReceiver extends BroadcastReceiver {
        private static final String LOG_TAG = "HomeReceiver";
        private static final String SYSTEM_DIALOG_REASON_KEY = "reason";
        private static final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
        private static final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
        private static final String SYSTEM_DIALOG_REASON_LOCK = "lock";
        private static final String SYSTEM_DIALOG_REASON_ASSIST = "assist";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.i(LOG_TAG, "onReceive: action: " + action);
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                // android.intent.action.CLOSE_SYSTEM_DIALOGS
                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
                Log.i(LOG_TAG, "reason: " + reason);

                if (SYSTEM_DIALOG_REASON_HOME_KEY.equals(reason)) {
                    LauncherActivity1.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                           goHome();
                        }
                    });
                    App.getINstance().setsetWaveformMode(2,1);
                    new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            App.getINstance().setsetWaveformMode(5,1);
                        }
                    },150);

                }
                else if (SYSTEM_DIALOG_REASON_RECENT_APPS.equals(reason)) {

                 Intent studentSettingIntent=new Intent("com.launcher.wkang.student.setting");
                 context.startActivity(studentSettingIntent);
//                 abortBroadcast();
                }


            }
        }

    }
    private void initRegionId(){
//        initDevice(LauncherActivity1.this);
        new RegisterClass().start();
    }
    @TargetApi(Build.VERSION_CODES.O)
    public void initDevice(Context context){
        Map<String,String> map=new HashMap<String, String>();
//        String deviceId=PhoneUtil.getDeviceId(context);
//        String deviceId="1234657";
        String registerId=getRegistrationID(context);
        if (registerId==null){
            return;
        }
        if (TextUtils.isEmpty(App.getINstance().deviceId)){
            App.getINstance().deviceId=PhoneUtil.getDeviceId(context);
        }
        map.put("category","学生");
        map.put("categoryId","2");
        map.put("deviceSerial",App.getINstance().deviceId);
        Log.d("LauncherActivity1","App.getINstance().deviceId"+App.getINstance().deviceId);
        Log.d("PushReceive","registerId="+registerId);
        map.put("reginId",registerId);
        if (!TextUtils.isEmpty(App.getINstance().deviceId)&&!"00000000".equalsIgnoreCase(App.getINstance().deviceId)) {
//            if (!App.getINstance().isRegister) {
                NetUtils.post(Url.register, map, new RegisterCallBack(context));
//            }
        }
    }

    private class RegisterCallBack implements Callback {
        private Context mContext;
        RegisterCallBack(Context context){
            mContext=context;
        }
        @Override
        public void onFailure(Call call, IOException e) {
            Log.d("Fragment2","registerIOException="+e.getMessage());

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Log.d("Fragment2","RegisterCallBackbody="+response.body());
            String body=response.body().string();
            Log.d("PushReceive","RegisterCallBack body="+body);
            try {
                JSONObject jsonObject=new JSONObject(body);
                int code=jsonObject.optInt("code");
                if (code==0){
                    App.getINstance().isRegister=true;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }
    private class Prohibit extends Thread{
        @Override
        public void run() {
            super.run();
            while (true) {

                try {
                    sleep(100000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private class RegisterClass extends Thread{
        @Override
        public void run() {
            super.run();
            while (!App.getINstance().isRegister){
                initDevice(LauncherActivity1.this);
                Log.d("LauncherActivity1","initDevice(LauncherActivity1.this);");
                try {
                    sleep(20*1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    private   class ProhibitTimerTask extends TimerTask{
        public void run(){
            doProhibit();
        }
    }

    private Handler doProhibitHandle=new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1){
                case SETDEFAULTITEM:
                    launcherFragment.setCurrentItem(0);
                    Log.d("LauncherActivity1","doProhibitHandle setCurrentItem(0)");
                    break;
                case HINTTEXTWHAT:
                    if (launcherFragment!=null) {
                        if (launcherFragment.getFragment1()!=null) {
                            launcherFragment.getFragment1().doProhibit(hintText);
                        }
                    }
                    break;
            }
        }
    };
}
